package com.iptv.player;

import com.ihome.android.EAActivity;
import com.ihome.android.academy.R;
import com.ihome.android.academy.R.id;
import com.ihome.android.academy.R.layout;
import com.ihome.android.annotation.EAInjectView;
import com.ihome.android.common.ConfigUtil;
import com.ihome.android.util.log.LogUtil;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

@SuppressLint("NewApi")
public class BasicPlayer extends EAActivity {

	private String			TAG					= BasicPlayer.class.getSimpleName();
	private SurfaceHolder	surfaceHolder		= null;
	@EAInjectView(id = R.id.surfaceView)
	private SurfaceView		surfaceView			= null;
	private MediaPlayer		mediaPlayer			= null;
	private PlayStatus		currentStatus		= PlayStatus.Prepare;
	private String			playUrl				= null;
	private int				urlInx				= 0;
	private int				playType			= ConfigUtil.PLAY_TYPE_NONE;

	private final int		KEY_LEFT			= 21;
	private final int		KEY_RIGHT			= 22;
	private final int		KEY_OK				= 23;
	private final int		KEY_UP				= 19;
	private final int		KEY_DOWN			= 20;
	private final int		KEY_PAUSE			= 85;

	private static enum PlayStatus {
	Buffering, Prepare, Play, Stop, Pause;
	}

	private int			totaltime			= 0;
	private final int	MSG_UPDATE_PROGRESS	= 0x01;
	private final int	MSG_TIME_OUT		= 0x02;
	private final int	MSG_ERROR			= 0x03;
	public int			currentPosition		= 0;

	private int			errorCount			= 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		LogUtil.d(TAG, "onCreate");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.basic_player);
		init();
		initMediaPlayer();
		
		playUrl = this.getIntent().getExtras().getString(ConfigUtil.VIDEO_URL_KEY);
		
//		playUrl = "http://106.39.160.41/test01/M00/00/51/aiegH1WxwYmAZVYRAAAFzvcu5ew99.m3u8";
		
		LogUtil.d(TAG, "playUrl = " + playUrl);
		startPlay(playUrl);
	}

	@SuppressWarnings("deprecation")
	private void init() {
		surfaceView.setOnClickListener(new View.OnClickListener() {
			public void onClick(View paramAnonymousView) {

			}
		});

		surfaceHolder = surfaceView.getHolder();
		// surfaceHolder.setType(3);
		DisplayMetrics localDisplayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getRealMetrics(localDisplayMetrics);
		surfaceHolder.setFixedSize(localDisplayMetrics.widthPixels, localDisplayMetrics.heightPixels);
		surfaceHolder.setKeepScreenOn(true);
		LogUtil.e(TAG, "w:" + localDisplayMetrics.widthPixels + "\th :" + localDisplayMetrics.heightPixels);

		surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);// gy:different
																		// with
																		// surfaceHolder.setType(3);

		surfaceHolder.addCallback(new SurfaceHolder.Callback() {

			public void surfaceChanged(SurfaceHolder paramAnonymousSurfaceHolder, int paramAnonymousInt1, int paramAnonymousInt2, int paramAnonymousInt3) {
				LogUtil.d(TAG, "surfaceChanged");
			}

			public void surfaceCreated(SurfaceHolder paramAnonymousSurfaceHolder) {
				LogUtil.d(TAG, "surfaceCreated");
				mediaPlayer.setDisplay(surfaceHolder);
			}

			public void surfaceDestroyed(SurfaceHolder paramAnonymousSurfaceHolder) {
				LogUtil.d(TAG, "surfaceDestroyed");
			}

		});

	}

	private void initMediaPlayer() {

		LogUtil.d(TAG, "initMediaPlayer");
		try {
			mediaPlayer = new MediaPlayer();

			mediaPlayer.setAudioStreamType(3);
			
			
			
			mediaPlayer.setScreenOnWhilePlaying(true);

			mediaPlayer.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
				public void onBufferingUpdate(MediaPlayer mp, int percent) {
					// TODO Auto-generated method stub
					LogUtil.i("TAG-onBufferingUpdate", percent + "|" + mp.getCurrentPosition());
				}
			});

			mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
				public boolean onError(MediaPlayer paramAnonymousMediaPlayer, int paramAnonymousInt1, int paramAnonymousInt2) {
					LogUtil.d(TAG, "setOnErrorListener > onError: paramAnonymousInt1 = " + paramAnonymousInt1 + "\t paramAnonymousInt2 = " + paramAnonymousInt2);
					doError();
					return true;
				}
			});
			mediaPlayer.setOnInfoListener(new MediaPlayer.OnInfoListener() {
				public boolean onInfo(MediaPlayer mp, int what, int extra) {
					LogUtil.d(TAG, "---------setOnInfoListener ---------");
					switch (what) {
					case MediaPlayer.MEDIA_INFO_BUFFERING_START:
						currentStatus = PlayStatus.Buffering;
						break;
					case MediaPlayer.MEDIA_INFO_BUFFERING_END:
						currentStatus = PlayStatus.Play;
						break;
					default:
						break;
					}

					return true;

				}
			});
			return;
		} catch (Exception localException) {
			LogUtil.d(TAG, "initMediaPlayer Exception:" + localException);
		}

	}

	private void startPlay(String url) {
		// doPlay();
		doReset();
		if (url != null) {
			try {
				mediaPlayer.setDataSource(url);
			} catch (Exception e) {
				e.printStackTrace();
				LogUtil.d(TAG, "setDataSource error !, do nothing");
				return;
			}
		}
		else {
			LogUtil.d(TAG, "url == null, to do nothing");
			return;
		}

		if (mediaPlayer != null) {
			try {
				//				mediaPlayer.prepare();
				mediaPlayer.prepareAsync();
			} catch (Exception e) {
				e.printStackTrace();
			}

			doAfterPrepare();
		}
	}

	private void doAfterPrepare() {

		mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			public void onCompletion(MediaPlayer paramAnonymousMediaPlayer) {
				LogUtil.d(TAG, "---------onCompletion 1---------");
				doOnPlayComplete();
			}
		});

		mediaPlayer.setOnSeekCompleteListener(new MediaPlayer.OnSeekCompleteListener() {
			public void onSeekComplete(MediaPlayer paramAnonymousMediaPlayer) {
				Log.d(TAG, "---------onSeekComplete ---------");
			}
		});

		mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
			private void seekToPlay(MediaPlayer paramAnonymousMediaPlayer) {}

			public void onPrepared(MediaPlayer paramAnonymousMediaPlayer) {
				LogUtil.d(TAG, "######### on prepared #######");
				notifyToStart();
			}
		});

	}

	private Handler	mHandler	= new Handler() {
									public void handleMessage(Message msg) {
										switch (msg.what) {
										case MSG_UPDATE_PROGRESS:
											currentPosition = mediaPlayer.getCurrentPosition();

											if (currentPosition < -3000) {
												doOnPlayComplete();
											}

											Log.d(TAG, "currentPosition ======= " + currentPosition);
											break;
										case MSG_TIME_OUT:
											break;
										case MSG_ERROR:
											break;
										default:
											break;
										}

									}
								};

	// gy:需添加状态buffering preparing playing pause stop destroy
	public void doPlay() {
		Log.d(TAG, "----->doPlay");
		if (mediaPlayer != null && currentStatus == PlayStatus.Pause) {
			mediaPlayer.start();
			currentStatus = PlayStatus.Play;
			Log.d(TAG, "mediaPlayer.start()");
		}
	}

	public void doPause() {
		Log.d(TAG, "---->doPause");
		if ((mediaPlayer != null) && (currentStatus == PlayStatus.Play)) {
			currentStatus = PlayStatus.Pause;
			mediaPlayer.pause();
			Log.d(TAG, "mediaPlayer.pause()");
		}
	}

	public void doStop() {
		Log.d(TAG, "--->doStop");
		if (mediaPlayer != null) {

			if ((currentStatus == PlayStatus.Play) || (currentStatus == PlayStatus.Pause) || (currentStatus == PlayStatus.Buffering)) {

			}

			mediaPlayer.stop();
			Log.d(TAG, "mediaPlayer.stop()");
			currentStatus = PlayStatus.Stop;
		}
	}

	public void doFastRewind(Boolean isFast) {
		int current = 0, target;
		int fastRewindVal = (isFast == true ? 1 : -1);

		//		showControllerBar();
		Log.d(TAG, "--->doFastRewind > isFast = " + isFast);
		if (mediaPlayer != null) {
			current = mediaPlayer.getCurrentPosition();
		}

		if (playType == ConfigUtil.PLAY_TYPE_VOD) {
			target = ConfigUtil.STEP_FAST_REWIND_VOD * fastRewindVal + current;
		}
		else if (playType == ConfigUtil.PLAY_TYPE_LIVE) {
			target = ConfigUtil.STEP_FAST_REWIND_LIVE * fastRewindVal + current;
		}
		else {
			target = ConfigUtil.STEP_FAST_REWIND_NONE * fastRewindVal + current;
		}
		seekTo(target);
	}

	public void release() {
		Log.d(TAG, "----------->release");
		if (mediaPlayer != null) {
			mediaPlayer.release();
			Log.d(TAG, "mediaPlayer.release()");
			currentStatus = PlayStatus.Prepare;
			mediaPlayer = null;
		}
	}

	public void seekTo(int paramInt) {
		Log.d(TAG, "----------->seekTo");

		if (mediaPlayer != null) {
			// currentPos = 3000 + mediaPlayer.getCurrentPosition();
			if (paramInt > totaltime) {
				mediaPlayer.seekTo(-1000 + paramInt);
				return;
			}

			if (paramInt < 1000) {
				mediaPlayer.seekTo(1000);
				return;
			}
			mediaPlayer.seekTo(paramInt);
		}
	}

	private void doReset() {
		LogUtil.d(TAG, "--->doReset");
		if (mediaPlayer != null) {
			mediaPlayer.reset();
			Log.d(TAG, " mediaPlayer.reset()");
		}
	}

	public void notifyToStart() {
		LogUtil.d(TAG, "--->notifyToStart");
		mediaPlayer.start();
		currentStatus = PlayStatus.Play;
		totaltime = mediaPlayer.getDuration();
	}

	private void doOnPlayComplete() {
		Log.d(TAG, "--->doOnPlayComplete");
		setResult(RESULT_OK, getIntent());
		if (((currentStatus == PlayStatus.Play) || (currentStatus == PlayStatus.Pause) || (currentStatus == PlayStatus.Buffering)) && (mediaPlayer != null)) {
			mediaPlayer.stop();
			currentStatus = PlayStatus.Stop;
		}
		finish();
	}

	private void setResultIntent() {
		Intent localIntent = new Intent();
		Bundle localBundle = new Bundle();
		localIntent.putExtras(localBundle);
		setResult(-1, localIntent);
	}

	public boolean onKeyUp(int paramInt, KeyEvent paramKeyEvent) {
		Log.d(TAG, "onKeyUp keyCode-->" + paramInt);

		return super.onKeyUp(paramInt, paramKeyEvent);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		Log.d(TAG, "onKeyDown keyCode-->" + keyCode);

		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(RESULT_CANCELED, getIntent());
			finish();
			return true;
		}

		if (playType == ConfigUtil.PLAY_TYPE_VOD || playType == ConfigUtil.PLAY_TYPE_LIVE) {
			switch (keyCode) {
			case KEY_LEFT:
				Log.d(TAG, "onKeyDown:KEY_LEFT");
				doFastRewind(false);
				return true;
			case KEY_RIGHT:
				doFastRewind(true);
				return true;
			case KEY_OK:
			case KEY_PAUSE:
				if (currentStatus == PlayStatus.Play) {
					doPause();
				}
				else if (currentStatus == PlayStatus.Pause) {
					doPlay();
				}
				else {}
				return false;
			default:
				break;
			}
		}

		return super.onKeyDown(keyCode, event);
	}

	// gy:android按键调用顺序：dispatchKeyEvent--->return false --> onKeyDown/onKeyUp
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) { // gy:用于拦截按键或对按键进行其他处理
		int keyCode = event.getKeyCode();
		int action = event.getAction();

		Log.d(TAG, "dispatchKeyEvent:keycode = " + keyCode + " action = " + action);
		if (keyCode == 24 && action == KeyEvent.ACTION_DOWN) {

		}
		return super.dispatchKeyEvent(event);
	}

	protected void onDestroy() {
		Log.d(TAG, "onDestroy");
		super.onDestroy();
		currentPosition = 0;

		release();
	}

	private void doError() {
		Log.e(TAG, "--->doError");
		errorCount = errorCount + 1;
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			mediaPlayer.reset();
			Log.d(TAG, " mediaPlayer.reset()");
		}

		new Thread() {
			public void run() {
				//				VoolePlayerActivity.notifyRestartProxy();
				SystemClock.sleep(300L);
				Message localMessage = Message.obtain();
				localMessage.what = MSG_ERROR;
				if (mHandler != null) {
					Log.e(TAG, "doError > send error msg");
					mHandler.sendMessage(localMessage);
				}
			}
		}.start();
	}

	private BroadcastReceiver	screenreceiver	= new BroadcastReceiver() {
													public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
														Log.i(TAG, "onReceive" + paramAnonymousIntent.getAction());
													}
												};

	private class ReleaseBroadcastReceiver extends BroadcastReceiver {
		private ReleaseBroadcastReceiver() {}

		public void onReceive(Context paramContext, Intent paramIntent) {
		}
	}

	class MySeekbar implements OnSeekBarChangeListener {
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			Log.d(TAG, "MySeekbar > onProgressChanged");
		}

		//gy:never used unless on cell phone or pad
		public void onStartTrackingTouch(SeekBar seekBar) {
			Log.d(TAG, "MySeekbar > onStartTrackingTouch");
		}

		//gy:never used unless on cell phone or pad
		public void onStopTrackingTouch(SeekBar seekBar) {
			Log.d(TAG, "MySeekbar > onStopTrackingTouch");
		}

	}

	protected void onStop() {
		Log.d(TAG, "BasicPlayer > onStop");
		super.onStop();
		if (mediaPlayer != null) {
			mediaPlayer.stop();
			Log.d("VoolePlayerActivity", "mediaPlayer.stop()");
		}
	}
}
